<template>
  <div class="freight-management">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span class="title">运费管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleCalculate">
              <el-icon><Operation /></el-icon>
              运费计算
            </el-button>
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增运费模板
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="模板名称">
          <el-input v-model="searchForm.name" placeholder="请输入模板名称" clearable />
        </el-form-item>
        <el-form-item label="计费方式">
          <el-select v-model="searchForm.chargeType" placeholder="请选择计费方式" clearable>
            <el-option label="按重量" value="weight" />
            <el-option label="按体积" value="volume" />
            <el-option label="按件数" value="quantity" />
            <el-option label="按距离" value="distance" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="active" />
            <el-option label="停用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column prop="name" label="模板名称" width="180" />
        <el-table-column prop="chargeType" label="计费方式" width="120">
          <template #default="{ row }">
            <el-tag>{{ getChargeTypeText(row.chargeType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="baseWeight" label="首重/首件" width="120" align="right">
          <template #default="{ row }">
            {{ row.baseWeight }} {{ getUnit(row.chargeType) }}
          </template>
        </el-table-column>
        <el-table-column prop="basePrice" label="首费(元)" width="120" align="right" />
        <el-table-column prop="additionalWeight" label="续重/续件" width="120" align="right">
          <template #default="{ row }">
            {{ row.additionalWeight }} {{ getUnit(row.chargeType) }}
          </template>
        </el-table-column>
        <el-table-column prop="additionalPrice" label="续费(元)" width="120" align="right" />
        <el-table-column prop="deliveryArea" label="配送区域" width="150" />
        <el-table-column prop="carrier" label="承运商" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              active-value="active"
              inactive-value="inactive"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleView(row)">
              <el-icon><View /></el-icon>
              详情
            </el-button>
            <el-button link type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button link type="primary" size="small" @click="handleCopy(row)">
              <el-icon><DocumentCopy /></el-icon>
              复制
            </el-button>
            <el-button link type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="模板名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入模板名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计费方式" prop="chargeType">
              <el-select v-model="formData.chargeType" placeholder="请选择计费方式">
                <el-option label="按重量" value="weight" />
                <el-option label="按体积" value="volume" />
                <el-option label="按件数" value="quantity" />
                <el-option label="按距离" value="distance" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="承运商" prop="carrier">
              <el-select v-model="formData.carrier" placeholder="请选择承运商">
                <el-option label="顺丰速运" value="sf" />
                <el-option label="圆通速递" value="yt" />
                <el-option label="中通快递" value="zt" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配送区域" prop="deliveryArea">
              <el-input v-model="formData.deliveryArea" placeholder="请输入配送区域" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">计费规则</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="`首${getUnitLabel(formData.chargeType)}`" prop="baseWeight">
              <el-input-number v-model="formData.baseWeight" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="首费(元)" prop="basePrice">
              <el-input-number v-model="formData.basePrice" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="`续${getUnitLabel(formData.chargeType)}`" prop="additionalWeight">
              <el-input-number v-model="formData.additionalWeight" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="续费(元)" prop="additionalPrice">
              <el-input-number v-model="formData.additionalPrice" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">其他设置</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="免邮条件">
              <el-input-number v-model="formData.freeShippingAmount" :min="0" :precision="2" placeholder="订单金额" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="额外费用">
              <el-input-number v-model="formData.extraFee" :min="0" :precision="2" placeholder="偏远地区等" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 运费计算对话框 -->
    <el-dialog
      v-model="calculateDialogVisible"
      title="运费计算"
      width="600px"
    >
      <el-form :model="calculateForm" label-width="120px">
        <el-form-item label="选择模板">
          <el-select v-model="calculateForm.templateId" placeholder="请选择运费模板">
            <el-option
              v-for="item in tableData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="重量(kg)">
          <el-input-number v-model="calculateForm.weight" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="体积(m³)">
          <el-input-number v-model="calculateForm.volume" :min="0" :precision="3" />
        </el-form-item>
        <el-form-item label="件数">
          <el-input-number v-model="calculateForm.quantity" :min="1" />
        </el-form-item>
        <el-form-item label="距离(km)">
          <el-input-number v-model="calculateForm.distance" :min="0" />
        </el-form-item>

        <el-divider />

        <el-alert
          v-if="calculatedFreight !== null"
          :title="`计算结果：${calculatedFreight} 元`"
          type="success"
          :closable="false"
          show-icon
        />
      </el-form>

      <template #footer>
        <el-button @click="calculateDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="calculateFreight">计算</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus, Search, Refresh, Edit, Delete, View, DocumentCopy, Operation
} from '@element-plus/icons-vue'

// 搜索表单
const searchForm = reactive({
  name: '',
  chargeType: '',
  status: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新增运费模板')
const formRef = ref(null)

// 表单数据
const formData = reactive({
  name: '',
  chargeType: '',
  carrier: '',
  deliveryArea: '',
  baseWeight: 1,
  basePrice: 0,
  additionalWeight: 1,
  additionalPrice: 0,
  freeShippingAmount: 0,
  extraFee: 0,
  remark: ''
})

// 运费计算
const calculateDialogVisible = ref(false)
const calculateForm = reactive({
  templateId: null,
  weight: 1,
  volume: 0.001,
  quantity: 1,
  distance: 0
})
const calculatedFreight = ref(null)

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
  chargeType: [{ required: true, message: '请选择计费方式', trigger: 'change' }],
  carrier: [{ required: true, message: '请选择承运商', trigger: 'change' }],
  baseWeight: [{ required: true, message: '请输入首重', trigger: 'blur' }],
  basePrice: [{ required: true, message: '请输入首费', trigger: 'blur' }]
}

// 获取计费方式文本
const getChargeTypeText = (type) => {
  const textMap = {
    weight: '按重量',
    volume: '按体积',
    quantity: '按件数',
    distance: '按距离'
  }
  return textMap[type] || type
}

// 获取单位
const getUnit = (type) => {
  const unitMap = {
    weight: 'kg',
    volume: 'm³',
    quantity: '件',
    distance: 'km'
  }
  return unitMap[type] || ''
}

// 获取单位标签
const getUnitLabel = (type) => {
  const labelMap = {
    weight: '重',
    volume: '体积',
    quantity: '件',
    distance: '距离'
  }
  return labelMap[type] || ''
}

// 加载数据
const loadData = () => {
  loading.value = true
  
  setTimeout(() => {
    tableData.value = [
      {
        id: 1,
        name: '标准快递运费',
        chargeType: 'weight',
        baseWeight: 1,
        basePrice: 10,
        additionalWeight: 1,
        additionalPrice: 5,
        deliveryArea: '全国',
        carrier: '顺丰速运',
        status: 'active',
        createTime: '2024-01-01 10:00:00'
      },
      {
        id: 2,
        name: '经济物流运费',
        chargeType: 'weight',
        baseWeight: 5,
        basePrice: 15,
        additionalWeight: 1,
        additionalPrice: 3,
        deliveryArea: '华东地区',
        carrier: '圆通速递',
        status: 'active',
        createTime: '2024-01-02 11:00:00'
      }
    ]
    pagination.total = 2
    loading.value = false
  }, 500)
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

// 重置
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增运费模板'
  dialogVisible.value = true
}

// 运费计算
const handleCalculate = () => {
  calculateDialogVisible.value = true
  calculatedFreight.value = null
}

// 计算运费
const calculateFreight = () => {
  if (!calculateForm.templateId) {
    ElMessage.warning('请选择运费模板')
    return
  }

  // 模拟计算
  const template = tableData.value.find(t => t.id === calculateForm.templateId)
  if (template) {
    let freight = template.basePrice
    const chargeValue = calculateForm[template.chargeType === 'weight' ? 'weight' : 
                                      template.chargeType === 'volume' ? 'volume' : 
                                      template.chargeType === 'quantity' ? 'quantity' : 'distance']
    
    if (chargeValue > template.baseWeight) {
      const additional = Math.ceil((chargeValue - template.baseWeight) / template.additionalWeight)
      freight += additional * template.additionalPrice
    }

    calculatedFreight.value = freight.toFixed(2)
  }
}

// 查看详情
const handleView = (row) => {
  ElMessage.info(`查看运费模板: ${row.name}`)
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑运费模板'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 复制
const handleCopy = (row) => {
  dialogTitle.value = '复制运费模板'
  Object.assign(formData, { ...row, name: `${row.name} - 副本` })
  dialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该运费模板吗？', '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
    loadData()
  })
}

// 状态改变
const handleStatusChange = (row) => {
  const status = row.status === 'active' ? '启用' : '停用'
  ElMessage.success(`已${status}运费模板: ${row.name}`)
}

// 提交表单
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success(dialogTitle.value.includes('新增') ? '创建成功' : '更新成功')
      dialogVisible.value = false
      loadData()
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  formRef.value?.resetFields()
}

// 分页改变
const handleSizeChange = () => {
  loadData()
}

const handleCurrentChange = () => {
  loadData()
}

onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.freight-management {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 16px;
      font-weight: 500;
    }

    .header-actions {
      display: flex;
      gap: 12px;
    }
  }

  .search-form {
    margin-bottom: 20px;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

